package cc.shacocloud.redis.study.lock.impl;

import cc.shacocloud.redis.study.util.codeBlock.CodeBlockMD;
import cc.shacocloud.redis.study.util.codeBlock.CodeBlockMDManage;
import cc.shacocloud.redis.study.util.redis.RedisUtil;
import cc.shacocloud.redis.study.lock.TokenLimiterLock;
import redis.clients.jedis.BuilderFactory;

@CodeBlockMD(mdDirPath = "/redis/lock", mdFileName = "tokenLimiterLock")
public class RedisTokenLimiterLock implements TokenLimiterLock {

    // 令牌最大数量
    private final String maxQuantity;

    // 锁名称
    private final String lockName;

    public RedisTokenLimiterLock(int maxQuantity, String lockName) {
        this.maxQuantity = String.valueOf(maxQuantity);
        this.lockName = lockName;
        // lua 脚本中有初始值设置，写在这里只是用于提醒
        RedisUtil.set(lockName, "0");
    }

    @Override
    public boolean acquire() {
        String script = CodeBlockMDManage.get(RedisTokenLimiterLock.class, "acquire");
        return RedisUtil.eval(BuilderFactory.BOOLEAN, script, 1, lockName, maxQuantity);
    }

    @Override
    public void release(int permits) {
        String release = CodeBlockMDManage.get(RedisTokenLimiterLock.class, "release");
        RedisUtil.eval(release, 1, lockName, String.valueOf(permits));
    }

}
